//
//  foodJiluViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/6/28.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "foodJiluViewController.h"
#import "foodPlanView.h"
#import "addFoodViewController.h"
#import "foodJilu.h"
#import "shanshiFenxiViewController.h"

#define foodSheRuInformation @"http://120.24.178.16:8080/Health/food/findUserfoodRecordByDay.do" //膳食获取量
#define deleteFood @"http://120.24.178.16:8080/Health/food/delUserFoodRecord.do"  //删除一条膳食纪录
#define foodJiluInformation @"http://120.24.178.16:8080/Health/food/findUserFoodRecord.do"  //膳食纪录信息

static dispatch_once_t onceToken;

@interface foodJiluViewController ()
@property (nonatomic,assign)CGFloat secH;//scrollView高度
@property (nonatomic,strong)UIScrollView *scrollView;
@property (nonatomic,assign)int viewTag; //方便后面判断点击的是哪个加按钮
@property (nonatomic,weak)UILabel *sheruLabel; //摄入过多或过少
@property (nonatomic,strong)NSMutableArray *breastFastArrayM;//早餐
@property (nonatomic,strong)NSMutableArray *lunchArrayM;//中餐
@property (nonatomic,strong)NSMutableArray *dinnerArrayM;//晚餐
@property (nonatomic,strong)NSMutableArray *breastFastPlusArrayM;//早加餐
@property (nonatomic,strong)NSMutableArray *lunchPlusArrayM;//中加餐
@property (nonatomic,strong)NSMutableArray *dinnerPlusArrayM;//晚加餐

@property (nonatomic,strong)NSArray *categoryArray;  //各餐的描述及时间数组

typedef enum
{
    //以下是枚举成员
    breastFast = 0, //早餐
    breastFastPlus, //早加餐
    lunch,          //中餐
    lunchPlus,      //中加餐
    dinner,         //晚餐
    dinnerPlus      //晚加餐
}CategoryTime;//枚举名称

@end

@implementation foodJiluViewController



-(NSArray *)categoryArray
{
    if(!_categoryArray)
    {
        _categoryArray = @[@"      早餐（06:30～08:30）",@"      早加餐",@"      午餐（11:30～12:30）",@"      午加餐",@"      晚餐（17:30～18:30）",@"      晚加餐"];
    }
    return _categoryArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"膳食记录";
    self.view.backgroundColor = [UIColor whiteColor];
    self.secH = 0.f;
    self.viewTag = 1;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.breastFastArrayM = [NSMutableArray array];
    self.lunchArrayM = [NSMutableArray array];
    self.dinnerArrayM = [NSMutableArray array];
    self.breastFastPlusArrayM = [NSMutableArray array];
    self.lunchPlusArrayM = [NSMutableArray array];
    self.dinnerPlusArrayM = [NSMutableArray array];
    self.secH = 0.f;
    [self getShanshiJiLuInformationFromServices];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    for (UIView *view in self.view.subviews) {
        [view removeFromSuperview];
    }
}

//时间label和scrollview布局
-(void)timelabelAndScrollViewLayout
{
    CGFloat startY = 70;  //各控件的初始y坐标
    [self setCrossLabelToView:self.view andY:startY];
    
    NSRange yearRang = {0,4};
    NSRange monthRang = {5,2};
    NSRange dayRang = {8,2};
    NSString *yearStr = [self.selectDateString substringWithRange:yearRang];
    NSString *monStr = [self.selectDateString substringWithRange:monthRang];
    NSString *dayStr = [self.selectDateString substringWithRange:dayRang];
    
    startY += 1;
    UILabel *timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, startY, kDeviceWidth / 2.0, 50)];
    timeLabel.backgroundColor = [UIColor whiteColor];
    timeLabel.text = [NSString stringWithFormat:@"      %@年%@月%@日",yearStr,monStr,dayStr];
    timeLabel.textColor = YMColor(98, 98, 98);
    [self.view addSubview:timeLabel];
    
    UILabel *sherulabel = [[UILabel alloc]initWithFrame:CGRectMake(kDeviceWidth / 2.0 - 30, startY, kDeviceWidth / 2.0, 50)];
    sherulabel.textAlignment = NSTextAlignmentRight;
    sherulabel.textColor = YMColor(72, 189, 35);
    self.sheruLabel = sherulabel;
    sherulabel.backgroundColor = [UIColor whiteColor];
    sherulabel.text = @"摄入过少";
    [self.view addSubview:sherulabel];
    startY += timeLabel.frame.size.height;
    
    [self setCrossLabelToView:self.view andY:startY];
    startY += 1;
    //创建scrollview
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, startY, kDeviceWidth, kDeviceHeight - startY)];
    self.scrollView = scrollView;
    scrollView.bounces = NO;//弹簧效果
    [self.view addSubview:scrollView];
    
    NSArray *dataArray = nil;
    for(int i = 0; i < 6;i ++)
    {
        [self kindOfCanLayoutToScrollView:self.scrollView andY:self.secH andTitleString:self.categoryArray[i] andBtnTag:i];
        switch (i) {
            case breastFast:
                dataArray = [self.breastFastArrayM copy];
                 break;
            case breastFastPlus:
                dataArray = [self.breastFastPlusArrayM copy];
                break;
            case lunch:
                dataArray = [self.lunchArrayM copy];
                 break;
            case lunchPlus:
                dataArray = [self.lunchPlusArrayM copy];
            break;
            case dinner:
                dataArray = [self.dinnerArrayM copy];
                break;
            case dinnerPlus:
                dataArray = [self.dinnerPlusArrayM copy];
                break;
            default:
                break;
        }
        [self eachOneFoodDisplay:(int)dataArray.count toScrollView:self.scrollView andArray:dataArray];
    }
    [self setCrossLabelToView:scrollView andY:self.secH];
    
    self.secH += 30;
    //复制到膳食记录按钮
    UIButton *copyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    copyButton.frame = CGRectMake(kDeviceWidth * 0.25, self.secH, kDeviceWidth * 0.5, kDeviceWidth * 0.5 / 3.8);
    copyButton.layer.cornerRadius = 10.0;
    copyButton.backgroundColor = YMColor(252, 160, 207);
    [copyButton setTitle:@"一键分析" forState:UIControlStateNormal];
    [copyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [scrollView addSubview:copyButton];
    [copyButton addTarget:self action:@selector(clickFenxiButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.secH += copyButton.frame.size.height + 30;
    
    UILabel *jiluLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.secH, kDeviceWidth, 40)];
    jiluLabel.text = @"完整记录六餐分析才准确";
    jiluLabel.textAlignment = NSTextAlignmentCenter;
    jiluLabel.textColor = YMColor(104, 104, 104);
    [scrollView addSubview:jiluLabel];
    self.secH += jiluLabel.frame.size.height;
    //红色横条
    UILabel *pinkLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.secH + 32, kDeviceWidth, 18)];
    pinkLabel.backgroundColor = YMColor(254, 206, 230);
    [scrollView addSubview:pinkLabel];
    scrollView.contentSize = CGSizeMake(kDeviceWidth, self.secH + 50);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getFoodInformationFromServices];
    });
}

/**从服务器获取膳食摄入情况*/
-(void)getFoodInformationFromServices
{
    [MBProgressHUD showMessage:@"正在拼命加载中，请稍后..."];
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"Account"] = [[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"];
    [mgr GET: foodSheRuInformation parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        [MBProgressHUD hideHUD];
        if(responseObject)
        {
//            YMLog(@"responseObject = %@",responseObject);
            NSDictionary *dataDic2 = [responseObject objectForKey:@"data2"];//返回总的卡路里
            NSString *eatEnergy = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"eatEnergy"]];  //吃了多少卡路里
            CGFloat goldEnergy = [[dataDic2 objectForKey:@"energy"]floatValue];
            
            if(goldEnergy * 0.95 >= [eatEnergy intValue])
            {
                self.sheruLabel.text = @"摄入过少";
                self.sheruLabel.textColor = YMColor(72, 189, 35);
            }
            else if(goldEnergy * 1.05 <= [eatEnergy intValue])
            {
                self.sheruLabel.text = @"摄入过量";
                self.sheruLabel.textColor = [UIColor redColor];
            }
            else
            {
                self.sheruLabel.text = @"摄入适中";
                self.sheruLabel.textColor = YMColor(72, 189, 35);
            }
            
        }else{
            
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"请求数据失败,请检查网络"];
    }];
}


/**点击一键分析功能*/
-(void)clickFenxiButton
{
    shanshiFenxiViewController *fenxi = [[shanshiFenxiViewController alloc]init];
    [self.navigationController pushViewController:fenxi animated:YES];
    fenxi.selectDateString = self.selectDateString;
}

/**没有食物的添加label*/
-(void)NoFoodWaringLabelToScrollView:(UIScrollView *)scrollView
{
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"foodPlanView" owner:nil options:nil];
    foodPlanView *foodView = [array firstObject];
    foodView.frame = CGRectMake(0,self.secH,kDeviceWidth,kDeviceHeight / 8.1);
    foodView.backgroundColor = YMColor(245, 245, 245);
    [scrollView addSubview:foodView];
    foodView.tag = self.viewTag ++;
    
    foodView.foodImage.image = [UIImage imageNamed:@"ssgl_nofood"];
    
    foodView.foodName.text = @"还没有记录";
    CGRect fram = foodView.foodWeight.frame;
    fram.size.width += 300;
    foodView.foodWeight.frame = fram;
    foodView.foodWeight.text = @"请点击＋号添加要记录的食物";
    
    [foodView.changeButton removeFromSuperview];
    self.secH += foodView.frame.size.height;
}

/**点击添加按钮*/
-(void)clickAddButton:(UIButton *)btn
{
    addFoodViewController *addFood = [[addFoodViewController alloc]init];
    [self.navigationController pushViewController:addFood animated:YES];
    addFood.selectDateString = self.selectDateString;
    addFood.btnTag = btn.tag;
}

/**创建各餐的食物列表*/
-(void)eachOneFoodDisplay:(int)count toScrollView:(UIScrollView *)scrollView andArray:(NSArray *)arrayM
{
    if(arrayM.count > 0)
    {
        for(int i = 0;i < count;i ++)
        {
            // loadNibNamed 会将名为AppInfoView中定义的所有视图全部加载出来，并且按照XIB中定义的顺序，返回一个视图的数组
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"foodPlanView" owner:nil options:nil];
            foodPlanView *foodView = [array firstObject];
            foodView.frame = CGRectMake(0,self.secH,kDeviceWidth,kDeviceHeight / 8.1);
            foodView.backgroundColor = YMColor(245, 245, 245);
            [scrollView addSubview:foodView];
            foodView.tag = self.viewTag ++;
            
            foodView.changeButton.layer.cornerRadius = 8.0;
            foodView.changeButton.layer.borderWidth = 1.0;
            foodView.changeButton.layer.borderColor = [YMColor(250, 193, 220)CGColor];
            [foodView.changeButton setTitle:@"删    除" forState:UIControlStateNormal];
            
            foodJilu *food = arrayM[i];
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",food.imgSrc]];
            [foodView.foodImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zonghe"]];
            
            foodView.foodName.text = [NSString stringWithFormat:@"%@",food.foodName];
            foodView.foodWeight.text = [NSString stringWithFormat:@"%.1f克",[food.weight floatValue]];
            foodView.changeButton.tag = [food.jiluID integerValue];
            [foodView.changeButton addTarget:self action:@selector(deleteFoodJilu:) forControlEvents:UIControlEventTouchUpInside];
            
            self.secH += foodView.frame.size.height;
            if(i != count - 1)
            {
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, self.secH, kDeviceWidth, 1)];
                label.backgroundColor = YMColor(224, 224, 224);
                [scrollView addSubview:label];
                self.secH += 1;
            }
        }
    }
    else
    {
         [self NoFoodWaringLabelToScrollView:scrollView];
    }
}

/**删除食物纪录*/
-(void)deleteFoodJilu:(UIButton *)btn
{
    [MBProgressHUD showMessage:@"正在拼命删除，请稍后..."];

    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"id"] = [NSString stringWithFormat:@"%ld",(long)btn.tag];
    [mgr GET: deleteFood parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideHUD];
        if([[responseObject objectForKey:@"code"] isEqualToString:@"0"])
        {
            for (UIView *view in self.view.subviews) {
                [view removeFromSuperview];
                
                self.breastFastArrayM = [NSMutableArray array];
                self.lunchArrayM = [NSMutableArray array];
                self.dinnerArrayM = [NSMutableArray array];
                self.breastFastPlusArrayM = [NSMutableArray array];
                self.lunchPlusArrayM = [NSMutableArray array];
                self.dinnerPlusArrayM = [NSMutableArray array];
                self.secH = 0.f;
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    dispatch_once(&onceToken, ^{
                        [self getShanshiJiLuInformationFromServices];
                    });
                    
                });
                [MBProgressHUD showSuccess:@"删除成功!"];
                [[NSUserDefaults standardUserDefaults]setObject:@"haveChanged" forKey:@"changed"];
            }
        }else{
            [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"请求数据失败,请检查网络"];
    }];
}

//早餐，早加餐，中餐，中加餐，晚餐，晚加餐统一布局
-(void)kindOfCanLayoutToScrollView:(UIScrollView *)scrollView andY:(CGFloat)y andTitleString:(NSString *)titleString andBtnTag:(NSInteger)btnTag
{
    UILabel *canLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y, kDeviceWidth, 40.f)];
    canLabel.text = titleString;
    canLabel.textColor = YMColor(191, 87, 141);
    canLabel.backgroundColor = YMColor(254, 233, 244);
    [scrollView addSubview:canLabel];
    self.secH += canLabel.frame.size.height;
    
    UIButton *addBtn = [[UIButton alloc]initWithFrame:CGRectMake(kDeviceWidth - 50, y + 5, 30, 30)];
    [addBtn setImage:[UIImage imageNamed:@"ssgl_addfood_small"] forState:UIControlStateNormal];
    addBtn.tag = btnTag;
    [scrollView addSubview:addBtn];
    [addBtn addTarget:self action:@selector(clickAddButton:) forControlEvents:UIControlEventTouchUpInside];
}

/**横线*/
-(void)setCrossLabelToView:(UIView *)view andY:(CGFloat)y
{
    UILabel *crossLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y, kDeviceWidth, 1)];
    crossLabel.backgroundColor = YMColor(214, 214, 214);
    [view addSubview:crossLabel];
}


/**从服务器上读取膳食记录的信息*/
-(void)getShanshiJiLuInformationFromServices
{
    [MBProgressHUD showMessage:@"正在拼命加载中，请稍后..."];
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[passValue passValue].passValueName forKey:@"account"];
    [params setObject:[passValue passValue].saveDataUserName forKey:@"username"];
    
    params[@"Account"] = [[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"];
    params[@"date"] = self.selectDateString;
    [mgr GET: foodJiluInformation parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        YMLog(@"responseObject = %@",responseObject);
        [MBProgressHUD hideHUD];
        if([[responseObject objectForKey:@"code"] isEqualToString:@"0"])
        {
            onceToken = 0;
            NSArray *dataArray = [responseObject objectForKey:@"data"];
            if(dataArray.firstObject != nil)
            {
                if(dataArray.count != 0)
                {
                    for (NSDictionary *dii in dataArray)
                    {
                        foodJilu *food = [foodJilu foodInfoWithDict:dii];
                        switch ([food.orderId intValue])
                        {
                            case breastFast:
                                [self.breastFastArrayM addObject:food];
                                break;
                            case breastFastPlus:
                                [self.breastFastPlusArrayM addObject:food];
                                break;
                            case lunch:
                                [self.lunchArrayM addObject:food];
                                break;
                            case lunchPlus:
                                [self.lunchPlusArrayM addObject:food];
                                break;
                            case dinner:
                                [self.dinnerArrayM addObject:food];
                                break;
                            case dinnerPlus:
                                [self.dinnerPlusArrayM addObject:food];
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }else{
            [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
        }
         [self timelabelAndScrollViewLayout];
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"请求数据失败,请检查网络"];
    }];
}


@end
